package com.wzh.frame.utils.checkup;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;

import com.wzh.frame.R;
import com.wzh.frame.utils.AppUtils;
import com.wzh.frame.views.FiexoDialog;
import com.wzh.frame.views.FlikerProgressBar;

import java.io.File;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;


/**
 * Created by admin on 2015/10/22.
 */
public class CheckUpdate {
    private String localVersion;//获取本地版本号
    private final int UPDATA_NONEED = 0;//不需要更新
    private final int UPDATA_CLIENT = 1;//通知用户更新
    private final int GET_UNDATAINFO_ERROR = 2;//获取信息出错
    private final int SDCARD_NOMOUNTED = 3;
    private final int DOWN_ERROR = 4;//下载出错
    private UpdataInfo info;
    Context context;
    SharedPreferences remeber;
    String path = null;
    boolean isAuto = false;
    private FiexoDialog checkProgress;

    public CheckUpdate(Context context) {
        this.context = context;
        remeber = context.getSharedPreferences(context.getPackageName(), Context.MODE_PRIVATE);
    }

    /***
     * 获取包名
     */
    private String getVersionName() throws Exception {
        //getPackageName()是你当前类的包名，0代表是获取版本信息
        PackageManager packageManager = context.getPackageManager();

        PackageInfo packInfo = packageManager.getPackageInfo(context.getPackageName(),
                0);
//        Log.e("package", "版本名"+packInfo.versionName);
        return packInfo.versionName;
    }

    public void checkUpAuto(String url) {
        try {
            isAuto = true;
            this.path = url;
            localVersion = getVersionName();
            CheckVersionTask cv = new CheckVersionTask();
            new Thread(cv).start();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public void checkUp(String url) {
        creatProssDialog();
        try {
            isAuto = false;
            this.path = url;
            localVersion = getVersionName();
            CheckVersionTask cv = new CheckVersionTask();
            new Thread(cv).start();


        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    private void creatProssDialog() {
        checkProgress = new FiexoDialog(context, FiexoDialog.PROGRESS_TYPE);
        checkProgress.setTitleText("检测更新……").show();
    }
    public class CheckVersionTask implements Runnable {
        InputStream is;

        public void run() {
            try {
//                Log.e("aaa", "111");
                URL url = new URL(path);
//                Log.e("aaa","222");
                HttpURLConnection conn = (HttpURLConnection) url
                        .openConnection();
//                Log.e("aaa","333");
                conn.setConnectTimeout(5000);
//                Log.e("aaa","444");
                conn.setRequestMethod("GET");
//                Log.e("aaa","555");
                int responseCode = conn.getResponseCode();
//                Log.e("responseCode",responseCode+"");
                if (responseCode == 200) {
                    // 从服务器获得一个输入流
                    is = conn.getInputStream();
                }
//                Log.e("is",is+"");
                info = UpdataInfoParser.getUpdataInfo(is);
//                Log.e("info",info+"");
                if (info.getVersion().equals(localVersion)) {
//                    Log.i(TAG, "版本号相同" + info.getVersion());
                    Message msg = new Message();
                    msg.what = UPDATA_NONEED;
                    handlerupdate.sendMessage(msg);
                    // LoginMain();
                } else {
//                    Log.i(TAG, "版本号不相同 "+info.getVersion());
                    Message msg = new Message();
                    msg.what = UPDATA_CLIENT;
                    handlerupdate.sendMessage(msg);
                }
            } catch (Exception e) {
                Message msg = new Message();
                msg.what = GET_UNDATAINFO_ERROR;
                handlerupdate.sendMessage(msg);
                e.printStackTrace();
            }
        }
    }

    private void dissMissCheckUp() {
        if (!isAuto)
            if (checkProgress != null) {
                if (checkProgress.isShowing()) {
                    checkProgress.dismiss();
                }
            }
    }



    Handler handlerupdate = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            super.handleMessage(msg);
            switch (msg.what) {

                case UPDATA_NONEED:
                    Log.e("WA==", msg.what + "");
                    dissMissCheckUp();
                    if (!isAuto) {
                        new FiexoDialog(context)
                                .setTitleText("不需要更新")
                                .show();
                    }
                    break;
                case UPDATA_CLIENT:
                    Log.e("WA==", msg.what + "");
                    //对话框通知用户升级程序
                    dissMissCheckUp();
                    if (isAuto) {
                        if (remeber.contains("date")) {
                            if (!remeber.getString("date", null).equals(getStringDateShort())) {
                                showUpdataDialog();
                            }
                        } else if (remeber.contains("verno")) {
                            if (!remeber.getString("verno", null).equals(info.getVersion())) {
                                showUpdataDialog();
                            }
                        } else {
                            showUpdataDialog();
                        }
                    } else {
                        showUpdataNowDialog();
                    }
                    Log.e("ver==", localVersion);
                    break;
                case GET_UNDATAINFO_ERROR:
                    Log.e("WA==", msg.what + "");
                    //服务器超时
                    dissMissCheckUp();
                    if (!isAuto) {
                        new FiexoDialog(context, FiexoDialog.ERROR_TYPE)
                                .setTitleText("获取服务器更新信息失败")
                                .show();
                    }
                    break;
                case DOWN_ERROR:
                    Log.e("WA==", msg.what + "");
                    //下载apk失败
                    dissMissCheckUp();
                    new FiexoDialog(context, FiexoDialog.ERROR_TYPE)
                            .setTitleText("下载新版本失败")
                            .show();
                    break;
            }
        }
    };

    private void showUpdataNowDialog() {
        new FiexoDialog(context, FiexoDialog.NORMAL_TYPE)
                .setTitleText("检测到有版本需要升级吗？")
                .setConfirmText("确定")
                .setCancelText("取消")
                .setConfirmClickListener(new FiexoDialog.OnFiexoClickListener() {
                    @Override
                    public void onClick(FiexoDialog fiexoDialog) {
                        downLoadApk();
                        fiexoDialog.dismiss();
                    }
                }).setCancelClickListener(new FiexoDialog.OnFiexoClickListener() {
            @Override
            public void onClick(FiexoDialog fiexoDialog) {
                    fiexoDialog.dismiss();
            }
        })
                .show();


//        new SweetAlertDialog(context, SweetAlertDialog.WARNING_TYPE)
//                .setTitleText("检测到有版本需要升级吗？")
//                .setConfirmText("确定")
//                .setCancelText("取消")
//                .setCustomImage(R.drawable.ic_launcher)
//                .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
//                    @Override
//                    public void onClick(SweetAlertDialog sweetAlertDialog) {
//                        Log.i("TAG下载更新", "下载apk,更新");
//                        downLoadApk();
//                        sweetAlertDialog.dismissWithAnimation();
//                    }
//                }).setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
//            @Override
//            public void onClick(SweetAlertDialog sweetAlertDialog) {
//                sweetAlertDialog.dismiss();
//            }
//        })
//                .showCancelButton(true)
//                .show();

    }


    /*
     *
	 * 弹出对话框通知用户更新程序
	 *
	 * 弹出对话框的步骤：
	 *  1.创建alertDialog的builder.
	 *  2.要给builder设置属性, 对话框的内容,样式,按钮
	 *  3.通过builder 创建一个对话框
	 *  4.对话框show()出来
	 */
    protected void showUpdataDialog() {
        final boolean[] isCheck = {false};
        FiexoDialog checkUpDialog = new FiexoDialog(context, FiexoDialog.CHECKUP_TYPE);
        checkUpDialog.setTitleText("发现新版本");
        checkUpDialog.setVerNo(info.getVersion());
        checkUpDialog.setVerSize(info.getVersionsize());
        checkUpDialog.setUpdateContent(info.getDescription());
        checkUpDialog.setCanceledOnTouchOutside(false);
        checkUpDialog.setCancelable(false);
        checkUpDialog.setConfirmText("立即更新");
        if (TextUtils.isEmpty(info.getIsforce())){
            if ("1".equals(info.getIsforce())){
                checkUpDialog.setCancelText("稍后提醒");
            }
        }
        checkUpDialog.setConfirmClickListener(new FiexoDialog.OnFiexoClickListener() {
            @Override
            public void onClick(FiexoDialog fiexoDialog) {
                downLoadApk();
                fiexoDialog.dismiss();
            }
        });
        checkUpDialog.setCancelClickListener(new FiexoDialog.OnFiexoClickListener() {
            @Override
            public void onClick(FiexoDialog fiexoDialog) {
                remeber.edit().clear().commit();
                if (isCheck[0]) {
                    remeber.edit().putString("verno", info.getVersion()).commit();
                } else {
                    remeber.edit().putString("date", getStringDateShort()).commit();
                }
                fiexoDialog.dismiss();
            }
        });
        checkUpDialog.setmChangeListener(new FiexoDialog.OnFiexoChangeListener() {
            @Override
            public void onChecked(boolean isChecked) {
                 isCheck[0] =isChecked;
            }
        });
        checkUpDialog.show();

//        final boolean[] ischecked = {false};
//        SweetAlertDialog sad = new SweetAlertDialog(context, SweetAlertDialog.HWZ_CHECKUP);
//        sad.setVerNo(info.getVersion());
//        sad.setVerSize(info.getVersionsize());
//        sad.setUpdateContent(info.getDescription());
//        sad.setConfirmText("立即更新");
//        if (!TextUtils.isEmpty(info.getIsforce())){
//            if (info.getIsforce().equals("1")) {
//                sad.setCancelText("稍后提醒");
//            } else {
//                sad.setCancelable(false);
//            }
//        }else {
//            sad.setCancelable(false);
//        }
//
//        sad.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
//            @Override
//            public void onClick(SweetAlertDialog sweetAlertDialog) {
//                Log.i("TAG下载更新", "下载apk,更新");
//                downLoadApk();
//                sweetAlertDialog.dismissWithAnimation();
//            }
//        }).setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
//            @Override
//            public void onClick(SweetAlertDialog sweetAlertDialog) {
//                remeber.edit().clear().commit();
//                Log.e("CGEC11111111======", ischecked[0] + "");
//                if (ischecked[0]) {
//                    remeber.edit().putString("verno", info.getVersion()).commit();
//                } else {
//                    remeber.edit().putString("date", getStringDateShort()).commit();
//                }
//
//                sweetAlertDialog.dismiss();
//            }
//        })
//                .setmChangeListener(new SweetAlertDialog.OnSweetChangeListener() {
//                    @Override
//                    public void onChecked(boolean isChecked) {
//                        ischecked[0] = isChecked;
//                        Log.e("CGEC======", ischecked[0] + "");
//                    }
//                })
//                .showCancelButton(true)
//                .show();

    }

    /**
     * 获取现在时间
     *
     * @return 返回短时间字符串格式yyyy-MM-dd
     */
    public static String getStringDateShort() {
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String dateString = formatter.format(currentTime);
        return dateString;
    }

    /*
     * 从服务器中下载APK
     */
    protected void downLoadApk() {
        FiexoDialog downDialog = new FiexoDialog(context, FiexoDialog.UPDATE_TYPE);
        downDialog.setCanceledOnTouchOutside(false);
        downDialog.setCancelable(false);
        downDialog.show();
        refreshData(downDialog);
    }

    private void refreshData(final FiexoDialog downDialog) {
        new Thread() {
            @Override
            public void run() {
                try {
                    File file = DownLoadManager.getFileFromServer(info.getUrl(), downDialog.getDowmProgress(), context);
                    sleep(3000);
                    downDialog.dismiss();
                    AppUtils.installApk(file, context);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

}
